package cn.edu.sdjzu.xg.eagle.dao;

import cn.edu.sdjzu.xg.eagle.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDaoInterface {
    private static UserDaoImpl userDaoImpl = new UserDaoImpl();
    public UserDaoImpl() {
    }
    public static UserDaoImpl getInstance() {
        return userDaoImpl;
    }

    @Override
    public  boolean add(User user, Connection connection) throws SQLException {
        PreparedStatement pstmt =
                connection.prepareStatement("insert into user"+
                        "(username,password,teacher_id)"+
                        " values(?,?,?)");
        pstmt.setString(1, user.getUsername());
        pstmt.setString(2, user.getPassword());
        pstmt.setLong(3, user.getTeacher().getId());

        int rowAffected = pstmt.executeUpdate();
        return rowAffected > 0;
    }
    public boolean delete(User user, Connection connection) throws SQLException {
        PreparedStatement pstmt_delete = connection.prepareStatement("delete from user where id = ?");
        pstmt_delete.setLong(1, user.getId());
        int rowAffect = pstmt_delete.executeUpdate();
        return rowAffect > 0;
    }

    @Override
    public void login(Connection connection, User user) throws SQLException {
        String sql_login = "SELECT * FROM user WHERE username = ? and password = ?";
        PreparedStatement pstmt_login = connection.prepareStatement(sql_login);
        pstmt_login.setString(1,user.getUsername());
        pstmt_login.setString(2,user.getPassword());
        ResultSet resultSet_login = pstmt_login.executeQuery();
        if (resultSet_login.next()){
            Long user_id = resultSet_login.getLong("id");
            user.setId(user_id);
        }
    }
}
